package qscript;

import org.qscript.Script;
import org.qscript.errors.EvaluationException;
import org.qscript.errors.SyntaxException;

import processing.core.PApplet;


public class SimpleGraph extends PApplet {

	// This will has no errors error
	String f0 = "sin(x) * cos(-2.1 * x)";
	// This will generate a syntax error
	String f1 = "sin(x) * cos(-2.1  x)";
	// This will generate an evaluation error
	String f2 = "sin(x) * cos(-2.1 + ' ' * x)";
	Script script;
	float lastX, lastY;

	public void setup(){
		size(400,200);
		//graph_101(f2);
		graph_201(f0);
	}

	/**
	 * This method demonstrates how to draw a graph in Basic Mode
	 */
	public void graph_101(String function){
		background(250,255,250);
		// Draw x axis
		stroke(0);
		strokeWeight(1);
		line(0, height/2, width, height/2);
		fill(0,64,0);
		text("Basic Mode", 6,16);
		// Create the script object
		script = new Script(function);
		// Parse the script. 
		script.parse();
		if(!script.isParsed()){
			text("### Syntax Error ###", 6, 32);
			return;
		}
		// The pasrer did not detect any syntax errors so we can now
		// use the script to evaluate the function for different 
		// values of x
		stroke(255,0,0);
		for(int px = 0; px < width; px++){
			// Scale the x pixel position to a sensible value for the 
			// and store it a script variable called x
			script.storeVariable("x", 0.04 * px);
			float y = script.evaluate().answer.toFloat();
			y = 60 * y + height/2;
			if(px == 0) { // Need two points to draw the graph line
				lastX = px;
				lastY = y;
			}
			else {
				line(lastX, lastY, px, y);
				lastX = px;
				lastY = y;
			}
		}
	}
	
	public void graph_201(String function){
		background(250,255,250);
		// Draw x axis
		stroke(0);
		strokeWeight(1);
		line(0, height/2, width, height/2);
		fill(0,64,0);
		text("Expert Mode", 6,16);
		// Create the script object
		script = new Script(function);
		// Parse the script. 
		try {
			script.parse_();
		} catch (SyntaxException e) {
			text("### Syntax Error ###", 6, 32);
			text(e.getMessage(), 6, 48);
			return;
		}
		// The pasrer did not detect any syntax errors so we can now
		// use the script to evaluate the function for different 
		// values of x
		stroke(255,0,0);
		for(int px = 0; px < width; px++){
			// Scale the x pixel position to a sensible value for the 
			// and store it a script variable called x
			script.storeVariable("x", 0.04 * px);
			float y = 0;
			try {
				y = script.evaluate_().answer.toFloat();
			} catch (EvaluationException e) {
				text("### Evaluation Error ###", 6, 32);
				text(e.getMessage(), 6, 48);
				return;
			}
			y = 60 * y + height/2;
			if(px == 0) { // Need two points to draw the graph line
				lastX = px;
				lastY = y;
			}
			else {
				line(lastX, lastY, px, y);
				lastX = px;
				lastY = y;
			}
		}
	}

}
